/**
 * 测试OPTIONS请求
 */

import express from "express";
import bodyParse from "body-parser";
import { Methods } from "./types";

const app = express();

// 解析body参数
// app.use(bodyParse.urlencoded({ extended: false }));
app.use(bodyParse.json());

app.use((req, res, next) => {
  const { headers, method } = req;
  //   console.log({ headers, method });

  res.setHeader("Access-Control-Allow-Origin", headers.origin as string); // 允许的源

  if (method === Methods.OPTIONS) {
    res.setHeader("Access-Control-Allow-Methods", headers["access-control-request-method"] as string); // 允许的请求方法
    res.setHeader("Access-Control-Allow-Headers", headers["access-control-request-headers"] as string); // 允许的请求头
    res.setHeader("Access-Control-Max-Age", "10"); // 预检过期时间-单位秒
    res.sendStatus(204); // 204 No Content
  } else {
    next();
  }
});

app.get("/options", (_, res) => {
  /* const data = [{ a: 1 }];
  res.send(data); */
  res.json("测试OPTIONS");
});

app.post("/options", (req, res) => {
  const { body } = req;
  console.log({ body });
  res.json("你好");
});

app.listen(3001, () => {
  console.log("测试OPTIONS服务器正在启动http://localhost:3001");
});
